package com.zy.springbootmybatis.controller.test1;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

/**
 * @program: 项目名
 * @description:pdf转成图片
 * 识别图片工具地址
 * https://digi.bib.uni-mannheim.de/tesseract/
 *
 * tesseract -v
 * E:\zy\Tesseract-OCR
 * E:\zy\tessdata_best-4.1.0\tessdata_best-4.1.0  1.3G提取图片文字包  todo
 * @author: manhengwei
 * @create: 2022-09-02 16:46
 **/
public class PDFUtil {
    public static void main(String[] args) throws IOException {
        //提取图片
       extractImages("D:\\赵阳简历.pdf");
        //提取文字
       extractText("D:\\赵阳简历.pdf");
        imagetext();//图片转换成文字

    }


    public static void imagetext() {
        long start = System.currentTimeMillis();
        System.out.println("开始OCR文字识图，请稍后...");
        //加载要识别的图片
        // File image = new File("D:\\zimu.png");
        // File image = new File("D:\\wei.png");
        // File image = new File("D:\\tes.png");
        // File image = new File("D:\\good1.png");
        //  File image = new File("D:\\uu.jpg");//失败
        File image = new File("D:\\kk.png");
        //设置配置文件夹微视、识别语言、识别模式
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("E:\\zy\\tessdata_best-4.1.0\\tessdata_best-4.1.0");
        //设置识别语言为中文简体，（如果要设置为英文可改为"eng"）
        tesseract.setLanguage("chi_sim");
        //tesseract.setLanguage("chi_sim");
        //使用 OSD 进行自动页面分割以进行图像处理
        tesseract.setPageSegMode(1);
        //设置引擎模式是神经网络LSTM引擎
        tesseract.setOcrEngineMode(1);
        //开始识别整张图片中的文字
        String result = null;
        try {
            result = tesseract.doOCR(image);
        } catch (TesseractException e) {
            throw new RuntimeException(e);
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("识别结束,耗时：" + time + " 毫秒，识别结果如下：");
        System.out.println();
        System.out.println(result.trim());
    }

    /**
     * 提取文本
     *
     * @return
     */
    public static void extractText(String path) {
        try {
            File fdf = new File(path);
            //通过文件名加载文档
            PDDocument pdd = Loader.loadPDF(fdf);
            //获取文档的页数
            int pageNumber = pdd.getNumberOfPages();
            //剥离器（读取pdf文件）
            PDFTextStripper stripper = new PDFTextStripper();
            //排序
            stripper.setSortByPosition(true);
            //设置要读取的起始页码
            stripper.setStartPage(1);
            //设置要读取的结束页码
            stripper.setEndPage(pageNumber);
            //  System.out.println(stripper.getText(pdd));
            //生成的txt的文件路径
            String docPath = path.substring(0, path.lastIndexOf(".")) + ".txt";
            File doc = new File(docPath);
            if (!doc.exists()) {
                doc.createNewFile();
            }
            //文件输出流
            FileOutputStream fos = new FileOutputStream(doc);
            Writer writer = new OutputStreamWriter(fos, "utf-8");
            stripper.writeText(pdd, writer);
            writer.close();
            fos.close();
            System.out.println("提取文本完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 提取图片
     *
     * @return
     */
    public static boolean extractImages(String path) {
        boolean result = true;
        try {
            File fdf = new File(path);
            //通过文件名加载文档
            PDDocument document = Loader.loadPDF(fdf);
            PDPageTree pages = document.getPages();
            Iterator<PDPage> iter = pages.iterator();
            //生成的txt的文件路径
            String imagePath = path.substring(0, path.lastIndexOf("."));
            System.out.println(imagePath);
            while (iter.hasNext()) {
                PDPage page = iter.next();
                PDResources resources = page.getResources();
                resources.getXObjectNames().forEach(e -> {
                    try {
                        if (resources.isImageXObject(e)) {
                            PDImageXObject imageXObject = (PDImageXObject) resources.getXObject(e);
                            BufferedImage bufferedImage = imageXObject.getImage();
                            System.out.println(bufferedImage);
                            ImageIO.write(bufferedImage, "png", new File(imagePath + "_" + e + ".png"));
                        }
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                });
                System.out.println("----------------------------------------------");
            }
            System.out.println("提取图片完成");
            //    document.save(fdf);
            document.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
        return result;
    }

}